package com.gin.no_gay_alliance.manager;

import androidx.annotation.NonNull;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.gin.jackson.utils.JacksonUtils;
import com.gin.nga.callback.JsonCallback;
import com.gin.nga.exception.NgaException;
import com.gin.nga.params.PageParam;
import com.gin.nga.response.body.ThreadBody;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Bundle;
import com.gin.no_gay_alliance.callback.Callback;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;

/**
 * 主题列表管理器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/8 11:48
 **/
public class TopicListManager {
    /**
     * 缓存对象
     */
    private final HashMap<String, Bundle<ThreadBody>> cache = new HashMap<>();


    /**
     * 执行请求
     *
     * @param ignoreCache 是否忽略缓存
     * @param param       参数
     * @param callback    回调
     */
    public void request(boolean ignoreCache, PageParam param, @NonNull Callback<ThreadBody> callback) {
        // 检查缓存
        String key = getKey(param);
        if (Bundle.checkCache(ignoreCache, cache, key, callback)) {
            return;
        }
        callback.beforeRequest();
        // 执行请求
        MyApplication.getClient().thread(param).async(new JsonCallback<ThreadBody>() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                callback.onFailure(call, e);
            }

            @Override
            public void onSuccess(ThreadBody body) {
                cache.put(key, new Bundle<>(body));
                if (ignoreCache) {
                    MyApplication.app.handler.toast("刷新成功");
                }
                callback.onSuccess(body);
            }

            @Override
            public void handleException(NgaException e) {
                callback.handleException(e);
            }
        });
    }

    /**
     * 根据param生成key
     *
     * @param param 参数
     * @return key
     */
    private static String getKey(PageParam param) {
        try {
            String typeName = param.getClass().getSimpleName();
            String value = JacksonUtils.MAPPER.writeValueAsString(param);
            return (typeName + value).replace("\n", "").replace(" ", "");
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
